/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System.Reflection;
using Castle.MonoRail.Framework;
using Yama.Util.CodeContracts;

namespace Yama.MVC.MonoRail.Filters
{
    ///<summary>
    /// Filter which fetches current actions <see cref="IActionFilter">action filters</see>
    /// and executes them.
    ///</summary>
    public class EnableActionFiltersFilter : Filter
    {
        IActionFilter[] actionFilters;

        protected override bool OnBeforeAction(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            actionFilters = GetExecutingActionsFilters(context.Services.CacheProvider, controller);
            bool filtersResult = true;

            foreach (IActionFilter filter in actionFilters)
            {
                if ((filter.ExecuteWhen & ExecuteWhen.BeforeAction) == ExecuteWhen.BeforeAction)
                    filtersResult &= filter.PerformBeforeAction(context, controller, controllerContext);
            }

            return filtersResult;
        }

        protected override void OnAfterAction(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            actionFilters = GetExecutingActionsFilters(context.Services.CacheProvider, controller);

            foreach (IActionFilter filter in actionFilters)
            {
                if (filter.ExecuteWhen == ExecuteWhen.Always || filter.ExecuteWhen == ExecuteWhen.AfterAction)
                    filter.PerformAfterAction(context, controller, controllerContext);
            }
        }

        protected override void OnAfterRendering(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            actionFilters = GetExecutingActionsFilters(context.Services.CacheProvider, controller);

            foreach (IActionFilter filter in actionFilters)
            {
                if (filter.ExecuteWhen == ExecuteWhen.Always || filter.ExecuteWhen == ExecuteWhen.AfterRendering)
                    filter.PerformAfterRendering(context, controller, controllerContext);
            }
        }

        /// <summary>
        /// Gets the <see cref="IActionFilter"/> attributes from current executing action
        /// </summary>
        static IActionFilter[] GetExecutingActionsFilters(ICacheProvider cache, IController iController)
        {
            Check.Require(iController is Controller, "Controller must inherit " + typeof(Controller));

            Controller controller = iController as Controller;
            string currentActionName = controller.Action;

            string cacheKey = string.Format("{0}/{1}/{2} action filters", controller.AreaName, controller.Name, currentActionName);

            if (!cache.HasKey(cacheKey))
            {
                object[] filters = GetActionFilters(controller); 

                if(filters == null)
                {
                    filters = GetDynamicActionFilters(controller);
                }

                if(filters == null)
                {
                    filters = new IActionFilter[0];
                }
                
                cache.Store(cacheKey, filters);
            }

            return (IActionFilter[])cache.Get(cacheKey);
        }

        static object[] GetActionFilters(Controller controller)
        {
            MethodInfo currentAction = controller.MetaDescriptor.Actions[controller.Action] as MethodInfo;
            
            return currentAction == null ? null : currentAction.GetCustomAttributes(typeof(IActionFilter), true);
        }

        static object[] GetDynamicActionFilters(Controller controller)
        {
            string currentActionName = controller.Action;

            if (controller.DynamicActions.ContainsKey(currentActionName))
            {
                IDynamicAction action = controller.DynamicActions[currentActionName];

                return action.GetType().GetMethod("Execute").GetCustomAttributes(typeof (IActionFilter), true);
            }

            return null;
        }
    }
}